const { exec } = require('child_process');
const path = require('path');
const child = require('child_process');
const { ffmpegPath } = require('./filePath')
const ffmpeg = path.join(__dirname, "./bin/ffmpeg.exe");
const logger = require('./Logger').getLogger('fileUtils');
const fs = require('fs');

const imgFan = (inputImagePath, outputImagePath) => {
    return new Promise((resolve, reject) => {
        // ffmpeg 命令
        const command = `${ffmpegPath} -i "${inputImagePath}" -vf "hflip" "${outputImagePath}"`;
        exec(command, function (err) {
            if (err) {
                logger.error('图像翻转失败', err);
                return reject(err.message);
            }
            resolve(outputImagePath);
        });

    });
}
const createFilePath = (path) => {
    // 检测目录是否存在
    if (!fs.existsSync(path)) {
        // 创建目录
        fs.mkdirSync(path);
    }
};


// const ffmpegCommand = `ffmpeg -i "${inputFilePath}" -c:v libwebp -quality 80 "${outputFilePath}"`;
const deleteFolder = function (folderPath) {
    if (fs.existsSync(folderPath)) {
        fs.readdirSync(folderPath).forEach(function (file) {
            const filePath = folderPath + '/' + file;
            if (fs.lstatSync(filePath).isDirectory()) {
                deleteFolder(filePath);
            } else {
                fs.unlinkSync(filePath);
            }
        });
        fs.rmdirSync(folderPath);
        console.log('文件夹删除成功！');
    } else {
        logger.info('文件夹不存在', folderPath);
    }
};

// 获取文件夹下所有文件
const getFilePath = (folderPath, extArr) => {
    const files = fs.readdirSync(folderPath);
    const filepaths = [];
    for (const file of files) {
        const filePath = path.join(folderPath, file);
        const stats = fs.statSync(filePath);
        if (stats.isFile()) {
            if (!extArr) {
                filepaths.push(filePath);
            }
            if (extArr && extArr.includes(path.extname(file))) {
                filepaths.push(filePath);
            }
        }
    }
    return filepaths;
};

const deleteFile = function (filePath) {
    // 删除文件
    if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
        console.log('文件删除成功！');
    } else {
        console.log('文件不存在！');
    }
}


// 将图片转为webp格式
const imgToWebp = function (inputFilePath, outputFilePath) {
    deleteFile(outputFilePath);
    return new Promise((resolve, reject) => {
        // ffmpeg 命令
        const command = `${ffmpegPath} -i "${inputFilePath}" -c:v libwebp -quality 80 "${outputFilePath}"`;
        exec(command, function (err) {
            if (err) {
                logger.error('图片转webp失败', err);
                return reject(err.message);
            }
            resolve(outputFilePath)
        });
    })
}


module.exports = {
    imgFan,
    deleteFolder,
    deleteFile,
    imgToWebp,
    getFilePath,
    createFilePath,
}
